/**
 * 测试pthread_join 函数
 * @author: sundx
 * @date: 2020-05-27 15:04:28
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-27 15:37:40
 */
#include <iostream>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
void *demo(void *argv);
int main() {
  pthread_t tid[5];
  int ret;
  for (int i = 0; i < 5; ++i) {
    int ret = pthread_create(&tid[i], NULL, demo, (void *)i);
    if (ret != 0) {
      std::cout << "pthread_create failed " << strerror(ret) << std::endl;
    }
  }
  long *value;
  for (int i = 0; i < 5; ++i) {
    ret = pthread_join(tid[i], (void **)&value);
    if (ret != 0) {
      std::cout << "pthread_join failed " << strerror(ret) << std::endl;
    }
    std::cout << "main thread: " << pthread_self()
              << " the subPthread : " << tid[i] << " return is :"
              << (long)value
              //这里是对value进行强转，因为demo函数将long型数据当作指针传出；
              << std::endl;
  }
  pthread_exit(NULL);
  return 0;
}

void *demo(void *argv) {
  long m = (long)argv;
  sleep(m);
  std::cout << "tid: " << pthread_self() << std::endl;
  return (void *)m;
}